#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
'''博主文章分类增删改查'''
from django.shortcuts import render
from django.shortcuts import HttpResponse
import json
from repository import models
from utils.custom_encoder import JsonCustomEncoder
from utils.pagination import Page
from forms import backend_forms
from ..auth.auth import check_login


@check_login
def category(request):
    """
    博主个人分类管理
    """
    if request.method == "GET":
        user_obj = models.UserInfo.objects.filter(nid=request.session.get('nid')).first()
        blog_nid = request.session.get('blog_nid')
        p = request.GET.get('p')
        current_page = int(p if p else 1)    # 获取当前页
        per_page_count = 3    # 每页显示3条数据

        if blog_nid:
            data_count = models.Category.objects.filter(blog_id=blog_nid).count()
        else:
            data_count = 0
        my_page = Page(
            current_page=current_page,
            data_count=data_count,
            per_page_count=per_page_count,
            pager_num=5,
        )
        if blog_nid:
            query_res = models.Category.objects.filter(blog_id=blog_nid).prefetch_related('article_set')[my_page.start:my_page.end]
        else:
            query_res = []
        page_str = my_page.page_str('/backend/category.html')
        return render(request, 'backend_category.html', {'title_list': query_res,'page_str': page_str})

    elif request.method == "POST":
        # 添加文章分类
        res_dict = {'status': True, 'errors': None, 'data': None}
        blog_nid = request.session.get('blog_nid')
        if blog_nid:
            category_nid = None
            form_obj = backend_forms.CategoryForm(category_nid,blog_nid, request.POST)
            if form_obj.is_valid():
                models.Category.objects.create(title=request.POST.get('title'),  blog_id=blog_nid)
                res_dict['status'] = True
            else:
                res_dict['status'] = False
                res_dict['errors'] = form_obj.errors.as_data()
        else:
            res_dict['status'] = False
            res_dict['errors'] = {'title':[{'messages': ['请先补充博客信息']},] }
        return HttpResponse(json.dumps(res_dict, cls=JsonCustomEncoder))


@check_login
def del_category(request):
    """
    删除文章分类
    """
    if request.method == "POST":
        res_dict = {'status': True, 'errors': None, 'data': None}

        models.Category.objects.filter(nid=request.POST.get('nid')).delete()
        return HttpResponse(json.dumps(res_dict))


@check_login
def edit_category(request):
    """
    编辑文章分类
    """
    if request.method == "POST":
        res_dict = {'status': True, 'errors': None, 'data': None}
        blog_nid = request.session.get('blog_nid')
        category_nid = request.POST.get('nid')

        form_obj = backend_forms.CategoryForm(category_nid, blog_nid, request.POST)
        if form_obj.is_valid():
            models.Category.objects.filter(nid=category_nid).update(**form_obj.cleaned_data)
            res_dict['status'] = True
        else:
            res_dict['status'] = False
            res_dict['errors'] = form_obj.errors.as_data()
        return HttpResponse(json.dumps(res_dict, cls=JsonCustomEncoder))